package com.kx.game.center.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.common.ServerEnum;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import com.kx.game.center.redis.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LocalManager {

    private static Logger logger = LoggerFactory.getLogger(LocalManager.class);

    /************** 用户 ***************/
    public String getLoginUserKey(String userId) {
//        String userKey = GSServices.userManager.getUserKey(userId, UserEnum.UserInfo.getIndex());
//        return RedisConstant.SERVER_LOGIN + "_" + userKey;
        return "";
    }

    /**
     * 用户登录的serverId
     */
    public String getServerIdByUserId(String userId) throws Exception {
        return GSServices.redisManager.hashGet(getLoginUserKey(userId), userId, String.class);
    }

    /**
     * 更新用户登录的serverId
     */
    public void updateServerIdByUserId(String userId, String serverId) throws Exception {
        GSServices.redisManager.hashSet(getLoginUserKey(userId), userId, serverId);
    }

    /**
     * 删除用户登录的serverId
     */
    public void deleteServerIdByUserId(String userId) throws Exception {
        GSServices.redisManager.hashDel(getLoginUserKey(userId), userId);
    }

    /************** 服务器 ***************/
    /**
     * 服务器的创建人数（key serverId）
     */
    public int getServerCreateNum(String serverId) throws Exception {
        return GSServices.redisManager.hashGet(RedisConstant.SERVER_CREATE_NUM, serverId, Integer.class);
    }

    /**
     * 更新服务器的创建人数（key serverId）
     */
    public void updateServerCreateNum(String serverId, int num) throws Exception {
        GSServices.redisManager.hashSet(RedisConstant.SERVER_CREATE_NUM, serverId, num);
    }

    /**
     * 更新服务器的创建人数（key serverId）
     */
    public void incrementServerCreateNum(String serverId, int num) throws Exception {
        GSServices.redisManager.hashIncrement(RedisConstant.SERVER_CREATE_NUM, serverId, num);
    }

    /**
     * 删除服务器的创建人数（key serverId）
     */
    public void deleteServerCreateNum(String serverId) throws Exception {
        GSServices.redisManager.hashDel(RedisConstant.SERVER_LOGIN, serverId);
    }

    /**
     * 服务器登录人数
     */
    public Integer getGSLoginCount(String serverId) throws Exception {
        Integer integer = GSServices.redisManager.hashGet(RedisConstant.GAME_SERVER_LOAD, serverId, Integer.class);
        if (integer == null)
            return 0;
        return integer;
    }

    /**
     * 更新服务器登录人数
     */
    public void updateGSLoginCount(String serverId, Integer loginNum) throws Exception {
        if (serverId == null || serverId.equals(""))
            return;
        GSServices.redisManager.hashSet(RedisConstant.GAME_SERVER_LOAD, serverId, loginNum);
    }

    /**
     * 变化数量
     *
     * @param num (-1||1)
     */
    public void incrementGSLoginCount(String serverId, Integer num) throws Exception {
        GSServices.redisManager.hashIncrement(RedisConstant.GAME_SERVER_LOAD, serverId, num);
    }

    /**
     * 删除服务器登录人数
     */
    public void deleteGameServerLoginCount(String serverId) throws Exception {
        GSServices.redisManager.hashDel(RedisConstant.GAME_SERVER_LOAD, serverId);
    }

    /************** 服务器列表 ***************/
    /**
     * 游戏服务器列表信息
     */
    public JSONObject getGameServerInfo(String serverId) throws Exception {
        return GSServices.redisManager.hashGet(RedisConstant.GAME_SERVER_LIST, serverId, JSONObject.class);
    }

    /**
     * 更新游戏服务器列表信息
     */
    public void updateGameServerInfo(String serverId, String ip, String gamePort, String gatePort, String connectIp, String connectPort,
                                     String state, String type, String time) throws Exception {
        if (serverId == null || serverId.equals(""))
            return;
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put(ip + "", port + "");
        jsonObject.put("serverId", serverId);
        jsonObject.put("ip", ip);
        jsonObject.put("gamePort", gamePort);
        jsonObject.put("gatePort", gatePort);
        jsonObject.put("connectIp", connectIp);
        jsonObject.put("connectPort", connectPort);
        jsonObject.put("state", state);
        jsonObject.put("type", type);
        jsonObject.put("time", time);
        GSServices.redisManager.hashSet(RedisConstant.GAME_SERVER_LIST, serverId, jsonObject);
    }

    /**
     * 更新游戏服务器状态
     */
    public void updateGameServerState(String serverId, ServerEnum state) throws Exception {
        if (serverId == null || serverId.equals(""))
            return;
        JSONObject jsonObject = getGameServerInfo(serverId);
        if (jsonObject == null)
            return;
        jsonObject.put("state", state.getIndex() + "");
        jsonObject.put("time", System.currentTimeMillis() + "");
        GSServices.redisManager.hashSet(RedisConstant.GAME_SERVER_LIST, serverId, jsonObject);
    }

    /**
     * 删除游戏服务器列表信息
     */
    public void deleteGameServerInfo(String serverId) throws Exception {
        GSServices.redisManager.hashDel(RedisConstant.GAME_SERVER_LIST, serverId);
    }

    /************** 网关列表 ***************/
    /**
     * 网关列表
     */
    public JSONObject getGatewayInfo(String id) throws Exception {
        return GSServices.redisManager.hashGet(RedisConstant.GATEWAY_LIST, id, JSONObject.class);
    }

    /**
     * 更新网关列表
     */
    public void updateGatewayInfo(String id, String ip, String port) throws Exception {
        if (id == null || id.equals(""))
            return;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", id);
        jsonObject.put("ip", ip);
        jsonObject.put("port", port);
        GSServices.redisManager.hashSet(RedisConstant.GATEWAY_LIST, id, JSONObject.class);
    }

    /**
     * 删除网关列表
     */
    public void deleteGatewayInfo(String id) throws Exception {
        GSServices.redisManager.hashDel(RedisConstant.GATEWAY_LIST, id);
    }

    /************** 网关 ***************/
    /**
     * 网关负载
     */
    public Integer getGatewayLoad(String id) throws Exception {
        Integer integer = GSServices.redisManager.hashGet(RedisConstant.GATEWAY_LOAD, id, Integer.class);
        if (integer == null)
            return 0;
        return integer;
    }

    /**
     * 更新网关负载
     */
    public void updateGatewayLoad(String id, Integer count) throws Exception {
        if (id == null || id.equals(""))
            return;
        GSServices.redisManager.hashSet(RedisConstant.GATEWAY_LOAD, id, count);
    }

    /**
     * 删除网关负载
     */
    public void deleteGatewayLoad(String id) throws Exception {
        GSServices.redisManager.hashDel(RedisConstant.GATEWAY_LOAD, id);
    }

    public void sendMessage(HttpServletResponse response, boolean result, LocalErrorResponseCode errorCode, String params) throws IOException {
        String message = generateResponse(result, errorCode, params);
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        out.write(message.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    public String generateResponse(boolean result, LocalErrorResponseCode errorCode, String params) {
        JSONObject jsonObject = new JSONObject();
        String response;
        if (result) {
            response = "ok";
        } else {
            response = "fail";
        }
        jsonObject.put("result", response);
        jsonObject.put("data", params);
        if (errorCode != null)
            jsonObject.put("code", errorCode.getIndex());
        return jsonObject.toString();
    }

    /**
     *  获取逻辑服用的
     * @param
     * @param response
     */
    public void sendMessage(JSONObject jsonObject, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(jsonObject.toJSONString().getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public JSONObject getJson(int result, String ip, String port) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        if (result == 1) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("ip", ip);
            jsonObject1.put("port", port);
            jsonObject.put("data", jsonObject1);
        }
        return jsonObject;
    }
}
